from typing import TypeVar, Generic, Type, List, Optional
import logging
from tortoise import Model
from fastapi import HTTPException

ModelType = TypeVar("ModelType", bound=Model)

class BaseService(Generic[ModelType]):
    """基础服务类，提供通用的CRUD操作，适配Tortoise ORM"""
    
    def __init__(self, model: Type[ModelType]):
        """
        初始化服务
        Args:
            model: Tortoise ORM 模型类
        """
        self.model = model
        self.logger = logging.getLogger(f"{__name__}.{self.__class__.__name__}")
        self.logger.debug(f"初始化服务: model={model.__name__}")

    async def get(self, id: int) -> Optional[ModelType]:
        """获取单个实体"""
        try:
            self.logger.debug(f"获取{self.model.__name__}记录: id={id}")
            instance = await self.model.get_or_none(id=id)
            if not instance:
                self.logger.warning(f"{self.model.__name__}记录不存在: id={id}")
            return instance
        except Exception as e:
            self.logger.error(f"获取{self.model.__name__}记录失败: {str(e)}", exc_info=True)
            raise HTTPException(status_code=500, detail=str(e))

    async def get_all(self) -> List[ModelType]:
        """获取所有实体"""
        try:
            self.logger.debug(f"获取所有{self.model.__name__}记录")
            instances = await self.model.all()
            self.logger.debug(f"成功获取{self.model.__name__}记录: count={len(instances)}")
            return instances
        except Exception as e:
            self.logger.error(f"获取所有{self.model.__name__}记录失败: {str(e)}", exc_info=True)
            raise HTTPException(status_code=500, detail=str(e))

    async def create(self, data: dict) -> ModelType:
        """创建实体"""
        try:
            self.logger.info(f"创建{self.model.__name__}记录: {data}")
            instance = await self.model.create(**data)
            self.logger.info(f"{self.model.__name__}记录创建成功: id={instance.id}")
            return instance
        except Exception as e:
            self.logger.error(f"创建{self.model.__name__}记录失败: {str(e)}", exc_info=True)
            raise HTTPException(status_code=400, detail=str(e))

    async def update(self, id: int, data: dict) -> Optional[ModelType]:
        """更新实体"""
        try:
            self.logger.info(f"更新{self.model.__name__}记录: id={id}, data={data}")
            instance = await self.get(id)
            if not instance:
                self.logger.warning(f"{self.model.__name__}记录不存在: id={id}")
                return None
            
            await instance.update_from_dict(data)
            await instance.save()
            self.logger.info(f"{self.model.__name__}记录更新成功: id={id}")
            return instance
        except Exception as e:
            self.logger.error(f"更新{self.model.__name__}记录失败: {str(e)}", exc_info=True)
            raise HTTPException(status_code=400, detail=str(e))

    async def delete(self, id: int) -> bool:
        """删除实体"""
        try:
            self.logger.info(f"删除{self.model.__name__}记录: id={id}")
            instance = await self.get(id)
            if not instance:
                self.logger.warning(f"{self.model.__name__}记录不存在: id={id}")
                return False
            
            await instance.delete()
            self.logger.info(f"{self.model.__name__}记录删除成功: id={id}")
            return True
        except Exception as e:
            self.logger.error(f"删除{self.model.__name__}记录失败: {str(e)}", exc_info=True)
            raise HTTPException(status_code=400, detail=str(e))
